package remote

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	D "gitee.com/dark.H/go-remote-repl/datas"
	"gitee.com/dark.H/go-remote-repl/lpc"
	"gitee.com/dark.H/go-remote-repl/thirtyapi"
	"github.com/schollz/progressbar/v3"
)

var (
	RegistedLocalFunc = map[string]func(acon *ApiConn, args string){
		"download": func(acon *ApiConn, id_len string) {
			fs := strings.SplitN(id_len, ":", 3)
			id := fs[1]
			len, _ := strconv.Atoi(fs[0])
			name := filepath.Join(os.TempDir(), id+".local.log")
			fmt.Println(id_len, "tmp fiel:", name)
			f, err := os.OpenFile(name, os.O_RDWR|os.O_APPEND|os.O_CREATE, os.ModePerm)

			if err != nil {
				log.Println("create file io err:", err)
				acon.Close()
				return
			}
			log.Println("Sync ok create file :", name)
			acon.SendMsg("ready ok")
			defer f.Close()
			defer acon.con.Close()

			var out io.Writer
			out = f
			bar := progressbar.DefaultBytes(
				int64(len),
				"dowlaod log from rpc",
			)
			out = io.MultiWriter(out, bar)
			io.Copy(out, acon.con)
		},
		"file sync": func(acon *ApiConn, args string) {
			var err error
			// fmt.Println(args)
			switch args {
			case "normal":
				file := lpc.FilePathInput()
				if file, err = filepath.Abs(file); err != nil {
					return
				}
				// fmt.Println("choose : ", file)
				// acon.SendMsg(file)
				// uuid := acon.ReadMsg()
				// fmt.Println(uuid)
				fmt.Println("uploaded in :", acon.SendFile(file))
			case "api":
				file := lpc.FilePathInput()
				if file, err = filepath.Abs(file); err != nil {
					return
				}
				fmt.Println("choose : ", file)
				// acon.SendMsg(file)
				if jsonData := thirtyapi.SimpleAPIParsse(file); jsonData != "" {
					dataJ := make(D.Gi)
					json.Unmarshal([]byte(jsonData), &dataJ)
					if _, err := os.Stat(dataJ["path"].(string)); err == nil {
						// acon.SendMsg(args)
						// uuid := acon.ReadMsg()
						// fmt.Println("uuid:", uuid)
						fmt.Println("uploaded in :", acon.SendFile(dataJ["path"].(string), dataJ))

					}
				}
			}
		},
	}
)

func ConnectApiMenu(con net.Conn) (api *ApiConn) {
	api = NewApiConn(con, "menu")
	return
}

func (acon *ApiConn) ToggleFunction(k string, args string) {
	fmt.Println("try toggle:", k)
	if f, ok := RegistedLocalFunc[k]; ok {
		f(acon, args)
	}
}

func RegistedClientHandler(name string, handler func(api *ApiConn, args string)) {
	locker.Lock()
	defer locker.Unlock()
	RegistedLocalFunc[name] = handler
}
